import { useHistory, useLocation } from 'react-router-dom'
import { InfiniteScroll, NavBar } from 'antd-mobile'

import styles from './index.module.scss'
import { getSearchResult } from '@/store/action/search'
import { useDispatch, useSelector } from 'react-redux'
import { useRef } from 'react'
import { RootState } from '@/types/store'
import ArticleItem from '@/pages/Home/ArticleItem'

const Result = () => {
  const history = useHistory()
  const location = useLocation()
  const dispatch = useDispatch()
  const keyword = decodeURI(location.search.replace('?keyword=', ''))
  // console.log(keyword)

  // useEffect(() => {
  //   dispatch(getSearchResult(keyword))
  // }, [dispatch, keyword])
  const {
    searchResult: { results = [] },
  } = useSelector((state: RootState) => state.search)
  const hasMore = results.length < 100
  const pageRef = useRef(1)
  // 加载状态
  const loadMore = async () => {
    await dispatch(getSearchResult(keyword, pageRef.current))
    pageRef.current++
  }

  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}>搜索结果</NavBar>
      <div className="article-list">
        <div className="article-item">
          {results.map((item) => (
            <ArticleItem key={item.art_id} article={item}></ArticleItem>
          ))}
          <InfiniteScroll
            loadMore={loadMore}
            hasMore={hasMore}
          ></InfiniteScroll>
        </div>
      </div>
    </div>
  )
}

export default Result
